package chanfoofoo ; 



import java.io.IOException; 

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.util.regex.Matcher; 
import java.util.regex.Pattern;

import java.util.logging.Logger;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;

import javax.mail.* ; 
import javax.mail.internet.* ;


@SuppressWarnings("serial")
public class cronjob01Servlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(cronjob01Servlet.class.getName());
	private User_manager um01 = new User_manager() ; 
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    	String tmpStr = null ;
    	StringBuffer info_01 = new StringBuffer("");  
    	StringBuffer log_01 = new StringBuffer("");
    	User currentUser = null ; 
    	GregorianCalendar cur_time = new GregorianCalendar(TimeZone.getTimeZone("Asia/Hong_Kong")) ;
    	
    	if (! isMarketTime(cur_time)) { 
    		info_01.append(cur_time) ; 
    	} else {
    		// String cur_quote_price = getQuote("3328") ;
    		// info_01.append( cur_quote_price ) ;  
    		String cur_quote_price = null ; 
    		StockQuote_manager stockManager = new StockQuote_manager() ;
    		stockManager.userAction("LIST") ; 
    		stockManager.list_all_to_console() ; 
    		StockQuote tmp_stock = null ; 	
    		for (int i = 0 ; i< stockManager.getList_StockQuote().size() ; i++) {
    			tmp_stock = stockManager.getList_StockQuote().get(i) ;
    			cur_quote_price = getQuote(tmp_stock.getStockcode()) ;
    			info_01.append( cur_quote_price + " ") ;
    			if (i == 0) {
    				currentUser = um01.getUserInfo(tmp_stock.getUser_id()) ; 
    			}
    		}    		
    		
    		if (currentUser != null) { 
		    	String hsiParamList[] = new String[3] ;   
		    	
		//    	Date cur_time = new Date();
		//    	DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL , Locale.US) ; 
		//    	fmt.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong")) ;
		//    	info_01.append(" at " + fmt.format(cur_time)) ;
		    	   
		        String tmp_str =  String.format(Locale.UK, "%1$td%1$tb%1$tY %1$tH:%1$tM %1$tz" , cur_time) ;     	
		    	info_01.append(" at " + tmp_str) ; 
		    		
		//    	hsiParamList[0] = "<span id=\"ctl00_ctl00_cphContent_cphContent_lblIndex\">(.+)</span>" ; // value 
		//    	hsiParamList[1] = "<span id=\"ctl00_ctl00_cphContent_cphContent_lblChange\">.+<span class=.+>(.+)</span></span>" ; // change
		//    	hsiParamList[2] = "<span id=\"ctl00_ctl00_cphContent_cphContent_lblPctChange\">.+<span class=.+>(.+)</span></span>" ; // change in %
		//    	hsiParamList[3] = "<span id=\"ctl00_ctl00_cphContent_cphContent_lblTurnover\">(.+)</span>" ; // turnover in B 	
		//    	tmpStr = getHSI("http://www.aastocks.com/en/market/hkindex.aspx?" , hsiParamList) ; 
		
		    	hsiParamList[0] = "<div class=\"qtxt_L_blue_white\">(.+)</div>"  ; // value 
		    	hsiParamList[1] = "<div class=\"qtxt_.+\"><img src=.+ border=\"0\" width=\"12\" height=\"12\">&nbsp;(.+)</div>" ; 
		    	hsiParamList[2] = "Turnover</div>.+<div class=\"qtxt_m_blue_white\">..(.+B)</div>" ; 	
		    	tmpStr = getRealTimeData("http://www.quamnet.com/quote.action" , hsiParamList) ; 
		    	
		    	String cur_HSI_price = "HSI : " + tmpStr.replace("," , "") ; 
		    	info_01.append(" , " + cur_HSI_price) ; 
		
		//    	GregorianCalendar cal = new GregorianCalendar() ; 
		//    	cal.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong")) ;	
		//        chanfoofoo.communication.sms SMS = new chanfoofoo.communication.sms() ;
		//        SMS.Add_SMS("mc4624@gmail.com", "29920696", cal , info_01.toString()) ; 
		    	
		    	log_01.append(info_01.toString()) ; 
//		    	log_01.append(" 01-Email Result : " +  
//		    			send_email("chan.foofoo@yahoo.com" , info_01.toString() , info_01.toString())) ;
//		    	log_01.append(" 02-Email Result : " +  
//		    			send_email("94124705@hotmailsms.com" , "AT-TEXT AT-NOFR" , info_01.toString())) ;
		    	if (! currentUser.getEmail_list().isEmpty()) { 
			    	log_01.append(" 01-Email Result : " +  
			    			send_email(currentUser.getEmail_list() , info_01.toString() , info_01.toString())) ;
			    	
			    	log_01.append(sms_google.create_event(cur_time , info_01.toString())) ; 
//			    	if (! currentUser.getMobile_no().isEmpty()) {
//				    	log_01.append(" 02-Email Result : " +  
//			    			send_email(currentUser.getMobile_no() + "@hotmailsms.com" , 
//	    					"AT-TEXT AT-NOFR" , info_01.toString())) ;
//			    	}
		    	}	
		    	System.out.println(log_01) ; 
		    	log.info(log_01.toString()) ; 
	    	//log.info(info_01.toString() + ", Email Result : " +  send_email(info_01.toString()) ) ;
    		}
    	} 
        resp.setContentType("text/plain") ;
        resp.getWriter().println(log_01) ;        
    }
    
    private String getRealTimeData(String in_url , String in_reg_match_str[]) {
    	StringBuffer http_data = new StringBuffer("") ;	
    	StringBuffer result = new StringBuffer("") ;
    	try {
            URL url = new URL(in_url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;

            while ((line = reader.readLine()) != null) {
            	http_data.append(line) ; 
            }
            // System.out.println(http_data) ;
            
            for (int i=0 ; i<in_reg_match_str.length ;i++) {
	            Pattern p = Pattern.compile(in_reg_match_str[i]);
	            Matcher m = p.matcher(http_data);
	
	            // if we find a match, get the group
	   
	            if (m.find())
	            {
	              // get the matching group
	              String codeGroup = m.group(1);
	              
	              String tmp_data  = null ;
	              // System.out.println(in_reg_match_str[i] + " " + codeGroup) ; 
	              if (codeGroup.indexOf('<') > 0) { 
	            	  tmp_data  = codeGroup.substring(0 , codeGroup.indexOf('<')) ;
	              } else {
	            	  tmp_data = codeGroup ; 
	              }
	           
//	              int int_val_only = VFP_lib.vfp_int(VFP_lib.vfp_val(tmp_data)) ;
//	              if (tmp_data.length() >= 5 && int_val_only != 0) {
//	            	  tmp_data = VFP_lib.vfp_str(int_val_only , 10,0) ;  
//	              }
	          
	              result.append(tmp_data.trim() ) ; 
	            }
            }
            reader.close();
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }    	    	
    	return result.toString() ; 
    }
    
    private String getQuote(String inStockCode) {
    	String para[] = new String[1] ; 
    	StringBuffer result = new StringBuffer("") ;
    	String url = "http://hk.finance.yahoo.com/q?s=" + 
    		VFP_lib.zerostr((int)VFP_lib.vfp_val(inStockCode) , 4)+ ".HK" ;
    	para[0] = "<div class=\"price\"><b>(\\S+\\s+)</b></div>" ; 
    	String tmp_str = getRealTimeData(url , para) ; 
    	result.append(inStockCode + "@" + tmp_str) ; 
        return result.toString() ; 
    }

    private String old_getQuote(String inStockCode) {
    	StringBuffer http_data = new StringBuffer("") ; 
    	StringBuffer result = new StringBuffer("") ;
    	try {
            URL url = new URL("http://hk.finance.yahoo.com/q?s=" + inStockCode + ".HK");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;

            while ((line = reader.readLine()) != null) {
            	http_data.append(line) ; 
            }
            	
            Pattern p = Pattern.compile("<div class=\"price\"><b>(\\S+\\s+)</b></div>");
            Matcher m = p.matcher(http_data);

            // if we find a match, get the group 
            if (m.find())
            {
              // get the matching group
              String codeGroup = m.group(1);
              
              // print the group
              // System.out.format("'%s'\n", codeGroup);
              result.append(inStockCode + "@") ; 
              result.append(codeGroup) ; 
            }
            reader.close();
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }    	
        return result.toString() ; 
    }
    
    private String send_email(String to_addr , String msgSub , String msgBody){  
        Properties props = new Properties();
        
        Session session = Session.getDefaultInstance(props, null);
        StringBuffer result = new StringBuffer("") ;  
        // String msgBody = "...";
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("win3721@gmail.com", "cronjob01Serverlet"));
//            msg.addRecipient(Message.RecipientType.TO,
//                             new InternetAddress("chan.foofoo@yahoo.com", "for chan.foofoo"));
            msg.addRecipient(Message.RecipientType.TO,
            		new InternetAddress(to_addr, ""));

            msg.setSubject(msgSub);
            msg.setText(msgBody);
            Transport.send(msg);
            result.append("OK" + msg.toString()) ; 
    
        } catch (Exception ex) {
        	result.append("FAIL-" + ex.toString()) ; 
        }
        return result.toString() ;     
    }
    
    private boolean isMarketTime(GregorianCalendar in_time) {
    	boolean result ;  
    	result = ( (in_time.get(Calendar.HOUR_OF_DAY) >= 9 && 
    			   	in_time.get(Calendar.HOUR_OF_DAY) <= 17) && 
        		  (in_time.get(Calendar.DAY_OF_WEEK) >= Calendar.MONDAY && 
        			in_time.get(Calendar.DAY_OF_WEEK) <= Calendar.FRIDAY)
        		)  ;
    	// result = true ; 
    	return result ;  
    }
}